package cn.edu.nju.ws.aquila.rdf.canonicalization.comparator;

import java.util.Comparator;

import cn.edu.nju.ws.aquila.rdf.canonicalization.labeled.LabeledResource;

import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;

/**
 * @author Gong Cheng
 * 
 */
public class LabeledResourceComparator implements Comparator<LabeledResource> {
	private Comparator<String> stringComparator = null;

	private Comparator<Literal> literalComparator = null;

	private LabeledResourceComparator() {
		/* Nothing */
	}

	public LabeledResourceComparator(Comparator<String> stringComparator,
			Comparator<Literal> literalComparator) {
		this.stringComparator = stringComparator;
		this.literalComparator = literalComparator;
	}

	public int compare(LabeledResource lr1, LabeledResource lr2) {
		RDFNode r1 = lr1.getRDFNode();
		RDFNode r2 = lr2.getRDFNode();

		if (r1.isURIResource()) {
			if (r2.isURIResource()) {
				return this.stringComparator.compare(((Resource) r1
						.as(Resource.class)).getURI(), ((Resource) r2
						.as(Resource.class)).getURI());
			}

			if (r2.isAnon()) {
				return -1;
			}

			if (r2.isLiteral()) {
				return -1;
			}
		}

		if (r1.isAnon()) {
			if (r2.isURIResource()) {
				return 1;
			}

			if (r2.isAnon()) {
				return lr1.getLabel() - lr2.getLabel();
			}

			if (r2.isLiteral()) {
				return -1;
			}
		}

		if (r1.isLiteral()) {
			if (r2.isURIResource()) {
				return 1;
			}

			if (r2.isAnon()) {
				return 1;
			}

			if (r2.isLiteral()) {
				return this.literalComparator.compare((Literal) r1
						.as(Literal.class), (Literal) r2.as(Literal.class));
			}
		}

		return 0;
	}

	public void close() {
		this.stringComparator = null;
		this.literalComparator = null;
	}
}